import { Models } from '../../../../common/typings/model'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import { Success, ParameterException } from '../../../../core/HttpException'
import emailLoginSchema from '../../../../common/apiValidate/system/auth/login'
import nameLoginSchema from '../../../../common/apiValidate/system/auth/nameLogin'
import validator from '../../../../middlewares/validator'
import { generateToken } from '../../../../common/utils/utils'
import WxManager from '../../../../service/WxManager'
import login from '../../../../common/apiValidate/system/auth/login'
import Config from '../../../../config/Config'
import RedisClient from '../../../../core/Redis'
import { checkCode } from '../../../../middlewares/code'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/auth`,
})

/*
 * 登录获取token的接口
 * @param { string } type ,100微信登录，101邮箱登录
 * @param { string } account ,邮箱, type为101时必填
 * @param { string } secret ,密码，type为101时必填
 * @param { string } code ，微信code ，type为100时必填
 * @return { string } token  成功返回token
 */
router.post('/login', validator(login, 'body'), checkCode, async (ctx) => {
  const { type: loginType, email, password, userName } = ctx.request.body
  const type = Number(loginType)
  let token, user
  switch (type) {
    //email登录
    case Config.LoginType.Email: {
      validator(emailLoginSchema)
      const res = await emailLogin(email as string, password as string)
      user = res?.user
      token = res?.token
      break
    }

    case Config.LoginType.WeChat: //小程序登录
      // v = await new MiniTokenValidator().validate(ctx)
      // token = await wxLogin(query.code)
      break
    case Config.LoginType.Name: {
      // 用户名登录
      validator(nameLoginSchema)
      const res = await nameLogin(userName as string, password as string)
      user = res?.user
      token = res?.token
      break
    }

    default:
      throw new ParameterException('没有相应的处理函数')
  }
  // await Token.saveToken(token)
  throw new Success({ user, token })
})

// /*
//  * 验证token是否通过的接口
//  * @param { string } token
//  * @return { Boolean } true  成功返回true
//  */
// router.post('/verify',async (ctx,next)=> {
//     const v = await new NotEmptyValidator().validate(ctx)
//     const query = ctx.request.body
//     const result = await Auth.verifyToken(query.token)
//     ctx.body = {
//         result
//     }
// })

// /*
//  * 注销登录
//  * @param { string } token
//  * @return { Boolean } true  成功返回true
//  */
// router.post('/cancellation',async (ctx,next)=> {
//     const v = await new NotEmptyValidator().validate(ctx)
//     const query = ctx.request.body
//     const result = await Token.deleteToken(query.token)
//     ctx.body = {
//         success: result
//     }
// })

// // email登录
async function emailLogin(email: string, password: string) {
  const res: Models.Result = await Mysql.command(`
      SELECT
      id,email,deleted,info,password,role_id
      FROM
          user
      where
          user.email = '${email}'
  `)
  return getToken(res, password)
}

function getToken(res: Models.Result, password: string) {
  if (!res.error) {
    const user = res.results[0]
    // const correct = await bcrypt.compareSync(password,user.password)
    const correct = checkPassword(password, user.password as string)
    if (!correct) {
      throw new ParameterException('密码不正确')
    }
    const token = generateToken(user.id as number, user.roleId)
    RedisClient.saveToken(token, user.id)
    return {
      token,
      user,
    }
  }
}

// 微信登录
async function wxLogin(code: string) {
  const token = await WxManager.codeToToken(code)
  return token
}

// name登录
async function nameLogin(name: string, password: string) {
  const res: Models.Result = await Mysql.command(`
        SELECT
        id,email,deleted,info,password,role_id
        FROM
            user
        where
            user.user_name = '${name}'
    `)
  return getToken(res, password)
}

/**
 * 校验密码是否正确
 * @param password1
 * @param password2
 * @returns
 */
function checkPassword(password1: string, password2: string): boolean {
  return password1 === password2
}

export default router
